from django.db import models

from django.db import models
from django.db.models.query import QuerySet
from django.db.models.manager import BaseManager

# <editor-fold desc="逻辑删除查询时过滤is_del字段为true的">
class DleQuerySet(QuerySet):
    def delete(self):
        self.update(is_del=True)

# 使用自己的QuerySet来管理各种操作 BaseManager.from_queryset(LyQuerySet)
class DleManager(BaseManager.from_queryset(DleQuerySet)):
    def __init__(self, *args, **kwargs):
        self.__add_is_del_filter = True
        super(DleManager, self).__init__(*args, **kwargs)

    def get_queryset(self, *args, **kwargs):

        queryset = super(DleManager, self).get_queryset(*args, **kwargs)

        # 判断用户是否主动传入is_del的筛选条件，如果主动传入，就不做自动筛选操作
        if self.__add_is_del_filter:
            # 过滤掉已删除的记录
            queryset = queryset.filter(is_del=False)

        return queryset

    def filter(self, *args, **kwargs):

        # 判断用户是否主动传入is_del的筛选条件，如果主动传入，就不做自动筛选操作
        if not kwargs.get('is_del') is None:
            self.__add_is_del_filter = False
        f = super(DleManager, self).filter(*args, **kwargs)
        return f
# </editor-fold>

# 基类
class BaseModel(models.Model):
    crate_time = models.DateTimeField(null=True, blank=True, auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(null=True, blank=True, auto_now_add=True,
                                       verbose_name="更新时间")

    class Meta:
        # 抽象类不创建表
        abstract = True

# 逻辑删除基类
class DelBaseModel(models.Model):
    crate_time = models.DateTimeField(null=True, blank=True, auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(null=True, blank=True, auto_now_add=True,
                                       verbose_name="更新时间")
    is_del = models.BooleanField(db_column='is_del',verbose_name='是否删除(false 0 未删除，1已删除)', default=False)

    # 使用自己的Manager对象来管理models
    objects = DleManager()

    class Meta:
        # 抽象类不创建表
        abstract = True

